//
//  WNGOtherViewController.swift
//  mggz
//
//  Created by QinWei on 2018/1/17.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Moya
import MJRefresh
import ObjectMapper
class WNGOtherViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    lazy var itemArray : [WNGCompanyMembersModel] = [WNGCompanyMembersModel]()
    var markArray:NSMutableArray?
    lazy var membersSelectArray : [String] = [String]()
    var page = 1
    var currentProject: LCProjectListModel? {
        willSet {
            self.currentProject = newValue
        }
    }
    
    var submitdialog:CustomDialog?
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "其他在职民工"
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "确定", fontSize: 17, self, #selector(rightItemClick))
        self.setupOtherWNGData()
        self.submitdialog = CustomDialog(frame: CGRect.zero, _title: "提示", _status: "需要将这些民工加入到\(ProjectName ?? "")项目中吗？", _submitclick: {
            self.submitdialog?.dismiss()
            
            guard let accountId = WWUser.sharedInstance.accountId else{
                return
            }
            guard ((self.currentProject?.MarketSupplyBaseID) != nil) else {
                return
            }
            guard self.membersSelectArray.count>0 else {
                WWProgressHUD.error("未选中目标")
                return
            }
            
            WWProgressHUD.showWithStatus("正在加入中...")
            LCAPiMainManager.request(.mwJoinTheProject(SupplyBaseId: (self.currentProject?.MarketSupplyBaseID)!, DataItemList: self.membersSelectArray as NSArray, AccountId: accountId)) { (result) in
                WWProgressHUD.dismiss()
                if case let .success(response) = result {
                    guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                        return
                    }
                    guard (jsonString["State"]) as! String == "OK" else{
                        return
                    }
                    
                    self.navigationController?.popViewController(animated: true)
                    //  self.guid = (jsonString["Guid"] as! String)
                }
            }
            
        })
        
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10)
        self.tableView.separatorInset = UIEdgeInsets.zero
        self.tableView.separatorStyle = .singleLine
        self.tableView.separatorColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.tableView.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        view.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.tableView.register(UINib.init(nibName: "WNGOtherCell", bundle: nil), forCellReuseIdentifier: "other")
        
        let tablehead = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refresh))
        tablehead?.stateLabel.isHidden = true
        self.tableView.mj_header = tablehead
        
        let tablefoot = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMore))
        tablefoot?.stateLabel.isHidden = true
        self.tableView.mj_footer = tablefoot
    }
    @objc func refresh(){
        self.page = 1
        self.setupOtherWNGData()
    }
    @objc func loadMore(){
        self.page += 1
        self.setupOtherWNGData()
        
    }
    @objc fileprivate func rightItemClick(){
        
        self.submitdialog?.show()
        
    }
    func setupOtherWNGData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard ((currentProject?.MarketSupplyBaseID) != nil) else {
            return
        }
    LCAPiMainManager.request(.GetOnlineWorkerOfCompany(pageIndex: self.page, pageSize: 25, AccountId: accountId, marketSupplyBaseID: (currentProject?.MarketSupplyBaseID)!)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let resultDic = jsonString["Result"] as? [String: AnyObject] else{
                    return
                }
                guard let itemsArr = resultDic["Items"] as? [[String: Any]] else{
                    return
                }
                let array = Mapper<WNGCompanyMembersModel>().mapArray(JSONArray: itemsArr)
                if self.page == 1{
                    self.itemArray.removeAll()
                    self.tableView.mj_header.endRefreshing()
                    if array == nil || array.count == 0{
                        
                    }else if array.count > 0 && array.count < 25{
                        self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    }else{
                        self.tableView.mj_footer.endRefreshing()
                    }
                }else{
                    if array.count < 25{
                        self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    }else{
                       self.tableView.mj_footer.endRefreshing()
                    }
                    
                }
                self.itemArray.append(contentsOf: array)
                self.markArray = NSMutableArray()
                for _ in 0..<self.itemArray.count{
                    self.markArray?.add("0")
                }
               self.tableView.reloadData()
               
            }
        }
    }
   
    
    
}
extension WNGOtherViewController : UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.itemArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : WNGOtherCell = tableView.dequeueReusableCell(withIdentifier: "other") as! WNGOtherCell
        cell.setupCompanyOnlineWorkerDataWithModel(self.itemArray[indexPath.row])
        let markStr : String = (self.markArray?[indexPath.row] as? String) ?? "0"
        if markStr == "0" {
            cell.coverView.isHidden = true
        }else if markStr == "1" {
            cell.coverView.isHidden = false
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let selectModel : WNGCompanyMembersModel = self.itemArray[indexPath.row]
        let markStr : String = self.markArray![indexPath.row] as! String
            if markStr == "0"{
            self.markArray?.replaceObject(at: indexPath.row, with: "1")
            self.membersSelectArray.append(selectModel.MigrantWorkerID!)
            }else if markStr == "1"{
                self.markArray?.replaceObject(at: indexPath.row, with: "0")
                for (index,value) in self.membersSelectArray.enumerated(){
                    if value == selectModel.MigrantWorkerID{
                        self.membersSelectArray.remove(at: index)
                    }
                }
            }
        self.tableView.reloadData()
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
}
